package com.example.classmanageapp;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.classmanageapp.Data.ClassInfo;
import com.example.classmanageapp.DataProvider.ClassInfoDBHelper;
import com.example.classmanageapp.DataProvider.ClassInfoSharedPreferences;
import com.example.classmanageapp.RecyclerViewRelated.WeekClass;
import com.example.classmanageapp.RecyclerViewRelated.WeekSelectAdapter;
import com.example.classmanageapp.Services.ClassRemindService;
import com.example.classmanageapp.utils.SysUtils;
import com.google.android.material.navigation.NavigationView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class MainStudentActivity extends AppCompatActivity {

    // 控件定义
    private ImageButton navButton;
    private DrawerLayout drawerLayout;
    private NavigationView navigationView;
    private LinearLayout setWeekLinearLayout;
    private PopupWindow popupWindow;
    private RecyclerView recyclerViewWeekSet;
    private TextView currentWeekTextView;
    private ImageView currentWeekImage;
    private TextView[] classesTextViews;
    private TextView currentMonthTextView;
    private TextView class1TimeTextView;
    private TextView class2TimeTextView;
    private TextView class3TimeTextView;
    private TextView class4TimeTextView;
    private TextView class5TimeTextView;
    private TextView class6TimeTextView;
    private TextView currentSemesterHeaderTextView;
    private TextView currentWeekHeaderTextView;
    private RelativeLayout settingHeaderRelativeLayout;
    private LinearLayout classMainLinearLayout;
    private NavigationView nav_view;
    private LinearLayout ll_head;
    private Context context;

    //  监听器定义
    private ClassNavViewListener classNavViewListener;
    private ClassButtonListener buttonListener;

    // Adapter
    private List<WeekClass> weekClassList = new ArrayList<>();

    // 需要的操作数据
    private String[] weeks;
    private List<ClassInfo> classInfos = new ArrayList<>();
    private int currentSemester;
    private int currentWeek;
    private String[] startTimes;
    private String[] endTimes;
    private String classNumbers;
    private int[] textViewIds;
    private Intent backRemind;

    // SharedPreference与SQLite的访写类
    private ClassInfoDBHelper classInfoDBHelper;
    private ClassInfoSharedPreferences classInfoSharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 设置状态栏格式，需要配合Style.xml
        if(Build.VERSION.SDK_INT >= 21){
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        setContentView(R.layout.activity_student_main);
        SysUtils.setStatusBarColor(this, true, 0);
        SysUtils.setSkin(this);
        context = this;

        // 初始化
        initiate();
    }

    // 更新界面
    private void updateView(){
        /*currentSemesterHeaderTextView.setText(getResources().getString(R.string.setting_current_semester_title) + currentSemester);
        currentWeekHeaderTextView.setText(getResources().getString(R.string.setting_current_week_title) + currentWeek);*/
        class1TimeTextView.setText(startTimes[0] + "\n" + "-" + "\n" + endTimes[0]);
        class2TimeTextView.setText(startTimes[1] + "\n" + "-" + "\n" + endTimes[1]);
        class3TimeTextView.setText(startTimes[2] + "\n" + "-" + "\n" + endTimes[2]);
        class4TimeTextView.setText(startTimes[3] + "\n" + "-" + "\n" + endTimes[3]);
        class5TimeTextView.setText(startTimes[4] + "\n" + "-" + "\n" + endTimes[4]);
        class6TimeTextView.setText(startTimes[5] + "\n" + "-" + "\n" + endTimes[5]);

        for (int i = 0; i < 42; i++){
            classesTextViews[i].setVisibility(View.INVISIBLE);
        }
        classInfos.clear();
        SQLiteDatabase sqLiteDatabase = classInfoDBHelper.getWritableDatabase();
        Cursor cursor = sqLiteDatabase.query("Classes",
                new String[]{"name", "teacher", "place", "day", "time", "start_week", "end_week", "semester"},
                "semester = ? and start_week <= ? and end_week >= ?",
                new String[]{String.valueOf(currentSemester), String.valueOf(currentWeek), String.valueOf(currentWeek)},
                null, null, null);
        if(cursor.moveToFirst()){
            do{
                String name = cursor.getString(cursor.getColumnIndex("name"));
                String teacher = cursor.getString(cursor.getColumnIndex("teacher"));
                String place = cursor.getString(cursor.getColumnIndex("place"));
                int day = cursor.getInt(cursor.getColumnIndex("day"));
                int time = cursor.getInt(cursor.getColumnIndex("time"));
                int start_week = cursor.getInt(cursor.getColumnIndex("start_week"));
                int end_week = cursor.getInt(cursor.getColumnIndex("end_week"));
                int semester = cursor.getInt(cursor.getColumnIndex("semester"));
                ClassInfo classInfoTemp = new ClassInfo(name, teacher, place, day, time, semester, start_week, end_week);
                classInfos.add(classInfoTemp);
            }while(cursor.moveToNext());
        }
        cursor.close();

        for(int i=0; i<classInfos.size(); i++){
            ClassInfo classInfo = classInfos.get(i);
            classesTextViews[(classInfo.getDay() - 1) * 6 + classInfo.getTime() - 1].setText(classInfo.getName()+"@"+classInfo.getPlace()+"-"+classInfo.getTeacher());
            classesTextViews[(classInfo.getDay() - 1) * 6 + classInfo.getTime() - 1].setVisibility(View.VISIBLE);
        }
        classNumbers = classInfoSharedPreferences.getClassNumber(this.currentSemester);

    }

    // 初始化工作
    private void initiate(){
        // 初始化监听器
        buttonListener = new ClassButtonListener();
        classNavViewListener = new ClassNavViewListener();

        // 初始化控件
        navButton = (ImageButton)findViewById(R.id.nav_button);
        drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
        navigationView = (NavigationView)findViewById(R.id.setting_student_nav_view) ;
        setWeekLinearLayout = (LinearLayout) findViewById(R.id.select_week_linear_layout);
        currentWeekTextView = (TextView)findViewById(R.id.select_week_button_text);
        currentWeekImage = (ImageView)findViewById(R.id.select_week_button_image);
        currentMonthTextView = (TextView)findViewById(R.id.month_text);
        class1TimeTextView = (TextView)findViewById(R.id.class_time_1_text);
        class2TimeTextView = (TextView)findViewById(R.id.class_time_2_text);
        class3TimeTextView = (TextView)findViewById(R.id.class_time_3_text);
        class4TimeTextView = (TextView)findViewById(R.id.class_time_4_text);
        class5TimeTextView = (TextView)findViewById(R.id.class_time_5_text);
        class6TimeTextView = (TextView)findViewById(R.id.class_time_6_text);
        classMainLinearLayout = (LinearLayout)findViewById(R.id.drawer_main);
        // 不能直接获取，要先获取抽屉的header，然后再寻找它的子布局
        View headerLayout = navigationView.getHeaderView(0);
        /*currentSemesterHeaderTextView = (TextView)headerLayout.findViewById(R.id.current_semester_text);
        currentWeekHeaderTextView = (TextView)headerLayout.findViewById(R.id.current_week_text);
        settingHeaderRelativeLayout = (RelativeLayout)headerLayout.findViewById(R.id.setting_back_header);*/

        // 初始化42个课程控件
        classesTextViews = new TextView[42];
        TypedArray textViewArray = getResources().obtainTypedArray(R.array.classes_id);
        textViewIds = new int[42];
        for (int i = 0; i < 42; i++){
            textViewIds[i] = textViewArray.getResourceId(i,0);
            classesTextViews[i] = (TextView) findViewById(textViewIds[i]);
            classesTextViews[i].setVisibility(View.INVISIBLE);
        }

        // 初始化数据存储类 并初始化数据
        classInfoSharedPreferences = new ClassInfoSharedPreferences(MainStudentActivity.this);
        classInfoDBHelper = new ClassInfoDBHelper(MainStudentActivity.this, "Classes.db", null, 1);
        this.currentWeek = this.classInfoSharedPreferences.getCurrentWeek();
        this.currentSemester = this.classInfoSharedPreferences.getCurrentSemester();
        this.startTimes = new String[6];
        this.endTimes = new String[6];
        startTimes[0] = classInfoSharedPreferences.getClass1StartTime();
        endTimes[0] = classInfoSharedPreferences.getClass1EndTime();
        startTimes[1] = classInfoSharedPreferences.getClass2StartTime();
        endTimes[1] = classInfoSharedPreferences.getClass2EndTime();
        startTimes[2] = classInfoSharedPreferences.getClass3StartTime();
        endTimes[2] = classInfoSharedPreferences.getClass3EndTime();
        startTimes[3] = classInfoSharedPreferences.getClass4StartTime();
        endTimes[3] = classInfoSharedPreferences.getClass4EndTime();
        startTimes[4] = classInfoSharedPreferences.getClass5StartTime();
        endTimes[4] = classInfoSharedPreferences.getClass5EndTime();
        startTimes[5] = classInfoSharedPreferences.getClass6StartTime();
        endTimes[5] = classInfoSharedPreferences.getClass6EndTime();
        this.classNumbers = classInfoSharedPreferences.getClassNumber(this.currentSemester);

        // 获取资源
        weeks = getResources().getStringArray(R.array.weeks_numbers);

        // 初始化界面
        currentWeekTextView.setText(weeks[currentWeek-1]);
        updateView();

        // 设置控件监听器
        navButton.setOnClickListener(this.buttonListener);
        navigationView.setNavigationItemSelectedListener(this.classNavViewListener);
        setWeekLinearLayout.setOnClickListener(this.buttonListener);

        // 初始化当前月份 使用Calender而不是使用Date（已经弃用）
        Calendar calendar = Calendar.getInstance();
        String currentMonth = (calendar.get(Calendar.MONTH)+1) + "月";
        this.currentMonthTextView.setText(currentMonth);

        // 后台服务
        backRemind = new Intent(MainStudentActivity.this, ClassRemindService.class);


        ll_head= (LinearLayout) headerLayout.findViewById(R.id.ll_head);
        ll_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(context, PersonActivity.class));
            }
        });
        //设置背景
        if(SysUtils.currentColor == 0){
            /*设置当前Activity的背景色*/
            Resources res = this.getResources();
            Drawable drawable = res.getDrawable(R.drawable.main_back_color_red);
            ll_head.setBackground(drawable);
        }else if (SysUtils.currentColor == 1){
            /*设置当前Activity的背景色*/
            Resources res = this.getResources();
            Drawable drawable = res.getDrawable(R.drawable.main_back_color_blue);
            ll_head.setBackground(drawable);
        }

    }

    // 更换皮肤
    private void changeSkin(){

        SysUtils.changeSkin(this);
        SharedPreferences sharedPreferences = getSharedPreferences("loginData",MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("currentColor",SysUtils.currentColor.toString());
        editor.apply();
        //设置背景
        if(SysUtils.currentColor == 0){
            /*设置当前Activity的背景色*/
            Resources res = this.getResources();
            Drawable drawable = res.getDrawable(R.drawable.main_back_color_red);
            ll_head.setBackground(drawable);
        }else if (SysUtils.currentColor == 1){
            /*设置当前Activity的背景色*/
            Resources res = this.getResources();
            Drawable drawable = res.getDrawable(R.drawable.main_back_color_blue);
            ll_head.setBackground(drawable);
        }
    }

    // 弹出选择 如果已经弹开那么就关闭
    private void showSelectWeek(){
        if(popupWindow!=null && popupWindow.isShowing()){
            popupWindow.dismiss();
            currentWeekImage.setImageResource(R.mipmap.arrow_drop_up_white);
            return;
        }
        View contentView = LayoutInflater.from(MainStudentActivity.this).inflate(R.layout.select_week_layout, null);
        popupWindow = new PopupWindow(contentView);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        initiateWeekRecycler(contentView);
        popupWindow.showAsDropDown(setWeekLinearLayout);
        currentWeekImage.setImageResource(R.mipmap.arrow_drop_down_white);
    }

    // 初始化选择周数的RecyclerView
    private void initiateWeekRecycler(View parent){
        recyclerViewWeekSet = (RecyclerView)parent.findViewById(R.id.set_week_recycler);
        weekClassList.clear();
        for(int i=0; i<20; i++){
            WeekClass weekClass = new WeekClass(weeks[i], "一共" + (Integer.valueOf(classNumbers.charAt(i)) - 48) + "节课");
            weekClassList.add(weekClass);
        }
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerViewWeekSet.setLayoutManager(linearLayoutManager);
        WeekSelectAdapter weekSelectAdapter = new WeekSelectAdapter(weekClassList);
        recyclerViewWeekSet.setAdapter(weekSelectAdapter);
        weekSelectAdapter.notifyDataSetChanged();
        // 设置每周被选择的监听事件
        weekSelectAdapter.setOnWeekItemClickListener(new WeekSelectAdapter.OnWeekItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                currentWeekTextView.setText(weeks[(int)view.getTag()]);
                currentWeek = (int)view.getTag()+1;
                classInfoSharedPreferences.setCurrentWeek(currentWeek, MainStudentActivity.this);
                updateView();
                popupWindow.dismiss();
                currentWeekImage.setImageResource(R.mipmap.arrow_drop_up_white);
            }
        });
    }

    // 自定义按钮点击响应事件
    private class ClassButtonListener implements View.OnClickListener{
        @Override
        public void onClick(View view) {
            switch (view.getId()){
                case R.id.nav_button:
                    if(popupWindow!=null && popupWindow.isShowing()){
                        popupWindow.dismiss();
                        currentWeekImage.setImageResource(R.mipmap.arrow_drop_up_white);
                    }
                    drawerLayout.openDrawer(GravityCompat.START);
                    break;
                case R.id.select_week_linear_layout:
                    showSelectWeek();
                    break;
            }
        }
    }

    // 自定义导航点击响应事件
    private class ClassNavViewListener implements NavigationView.OnNavigationItemSelectedListener{
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {

            Intent intent;
            drawerLayout.closeDrawers();
            switch (item.getItemId()){
                case R.id.setting_student_timetable:
                    break;
                case  R.id.setting_student_msg:
                    //跳转到 学生通知界面
                    intent = new Intent(MainStudentActivity.this,
                            MessageStudentActivity.class);
                    startActivity(intent);
                    break;
                case R.id.setting_student_change_skin_service:
                    changeSkin();
                    break;
                case R.id.setting_student_exit:
                    //跳转到 登录界面
                    intent = new Intent(MainStudentActivity.this,
                            LoginActivity.class);
                    startActivity(intent);
                    break;
            }
            return true;
        }
    }
}
